package uniandes.cupi2.tweetSpy.twitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import twitter4j.*;
import twitter4j.auth.*;
import uniandes.cupi2.tweetSpy.mundo.TweetSpy;

public class LoginTwitter {

	public final static String CONSUMER_KEY = "TKdRqkTFhfi2rlWrhrYZjg";
	public final static String CONSUMER_SECRET = "GDmiCXbZPL9vEZP4oESK9bH1MqmkOcOX0HVBlEBkUk";

	public static RequestToken requestToken;
	
	public static AccessToken atoken;
	
	public static void main(String args[]) throws Exception{
//		System.out.println( login( ) );
//		BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
//		System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
//		String pin = br.readLine();
//		conectar( pin );		
//		
//		SearchTweets.buscar("Bogota", atoken, null);
	}

	public static String login() throws ExceptionTwitter {
		try {
			
			Twitter twitter = twitter4j.TwitterFactory.getSingleton();
			twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
			requestToken = twitter.getOAuthRequestToken();
			return requestToken.getAuthorizationURL();
		} catch (Exception e) {
			throw new ExceptionTwitter(e.getMessage(),
					"Pidiendo token de inicio");
		}

	}

	public static void conectar(String pin, String clave ) throws ExceptionTwitter {
		AccessToken accessToken = null;
		Twitter twitter = TwitterFactory.getSingleton();
		try {
			accessToken = twitter.getOAuthAccessToken(requestToken, pin);
			atoken = accessToken;
			storeAccessToken(twitter.verifyCredentials().getId(), accessToken, clave);
		} catch (Exception e) {
			throw new ExceptionTwitter(e.getMessage(),
					"Conectando con el token");
		}
	}

	private static void storeAccessToken(long l, AccessToken accessToken, String clave)
			throws ExceptionTwitter {
		try {
			Twitter twitter = TwitterFactory.getSingleton();
			String screemName = twitter.getScreenName();
			User usuario = twitter.showUser( screemName );
			String urlFoto = usuario.getBiggerProfileImageURLHttps( );
			TweetSpy.getInstance( ).crearUsuario ( accessToken, usuario, screemName, urlFoto, clave );
		} catch (Exception e) {
			e.printStackTrace( );
			throw new ExceptionTwitter(e.getMessage(), "Guardando usuario");
		}
	}

}
